package com.mapforge.selection;

import java.awt.Rectangle;
import java.util.Iterator;
import java.util.List;

public class MultiSelectionIterator implements Iterator<ComparablePoint> {
	private int index;
	private List<Selection> selections;
	private Iterator<ComparablePoint> it;
	private Rectangle rect;

	public MultiSelectionIterator(List<Selection> selections, Rectangle rect) {
		index = -1;
		this.rect = rect;
		this.selections = selections;
		if (selections.size() > 0)
			nextIterator();
		else {
			it = new NullIterator<ComparablePoint>();
		}
	}

	@Override
	public boolean hasNext() {
		return it.hasNext();
	}

	private void nextIterator() {
		++index;
		if (rect == null) {
			it = selections.get(index).iterator();
			while (!it.hasNext() && (index + 1) < selections.size()) {
				++index;
				it = selections.get(index).iterator();
			}
		} else {
			it = selections.get(index).iterator(rect);
			while (!it.hasNext() && (index + 1) < selections.size()) {
				++index;
				it = selections.get(index).iterator(rect);
			}
		}
	}

	@Override
	public ComparablePoint next() {
		if (it.hasNext()) {
			ComparablePoint p = it.next();
			// no more points in this iterator, and have another iterator
			if (!it.hasNext() && (index + 1) < selections.size()) {
				nextIterator();
			}
			return p;
		} else {
			throw new IllegalStateException("Iterator has no more elements");
		}
	}

	@Override
	public void remove() {
		it.remove();
	}
}
